package com.unibert.podcastq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;

import com.unibert.items.ElementoComentario;
import com.unibert.items.ItemListBaseAdapterComentarios;
import com.unibert.podcastq.BD.BD;

public class Comments extends Activity {

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		new ObtenerComents().execute();
	}

	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private GestureDetector gestureDetector;
	View.OnTouchListener gestureListener;
	private static ListView listComentarios;
	private static ImageButton botonComentar;
	ArrayList<ElementoComentario> Lista = null;
	private static Integer id;
	private BD basededatoshelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		basededatoshelper = new BD(this,"QCU", null, 11);
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.push_left_in,R.anim.push_left_out);
		setContentView(R.layout.comments_layout);
		gestureDetector = new GestureDetector(Comments.this, new MyGestureDetector());
		gestureListener = new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				return gestureDetector.onTouchEvent(event);
			}
		};
		listComentarios = (ListView) findViewById(R.id.listComentarios);
		listComentarios.setOnTouchListener(gestureListener);
		if(com.unibert.podcastq.MainActivity.Lista!=null)
			listComentarios.setAdapter(new ItemListBaseAdapterComentarios(Comments.this, com.unibert.podcastq.MainActivity.Lista));
		botonComentar = (ImageButton) findViewById(R.id.buttonDejarComentario);
		botonComentar.setOnClickListener(new View.OnClickListener(){ 
			@Override
			public void onClick(View v) 
			{ 
				Intent intento2 = new Intent(Comments.this, Comentar.class);
				intento2.putExtra("id", id.toString());
				startActivity(intento2);

			}});
		Bundle extras = getIntent().getExtras();
		id=Integer.parseInt(extras.getString("id"));
		if(com.unibert.podcastq.MainActivity.Lista==null)
			new ObtenerComents().execute();
	}




	class MyGestureDetector extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					Comments.this.onBackPressed();

					overridePendingTransition(R.anim.push_right_in,R.anim.push_right_out);
					Comments.this.finish();
				}
			} catch (Exception e) {
				// nothing
			}
			return false;
		}

	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (gestureDetector.onTouchEvent(event))
			return true;
		else
			return false;
	} 

	private class ObtenerComents extends AsyncTask<String, String, String> {
		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			
			if(Lista.size()>0)
				listComentarios.setAdapter(new ItemListBaseAdapterComentarios(Comments.this, Lista));
			
			
		}
		ProgressDialog dialog;
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(Lista.size()>0)
				listComentarios.setAdapter(new ItemListBaseAdapterComentarios(Comments.this, Lista));
			com.unibert.podcastq.MainActivity.Lista = Lista;
			dialog.dismiss();
			

		}
		@Override
		protected void onPreExecute() {
			try {
				super.onPreExecute();
				dialog = new ProgressDialog(Comments.this);
				dialog.setTitle("Espera");
				dialog.setMessage("Cargando comentarios");
				dialog.setCancelable(true);
				dialog.setIndeterminate(true);
				dialog.show();
			} catch (final Exception e) {
				e.printStackTrace();
			}
		}
		@Override
		protected String doInBackground(String... params) {

			try {
				Lista = new ArrayList<ElementoComentario>();
				SQLiteDatabase db;
				String idmax="0";
				db = basededatoshelper.getReadableDatabase();	
				String[] arg = {"id", "nombre", "comentario"};
				String[] where = {""+id};
				Cursor cursor = db.query("COMENTARIOS",arg , "podcast=?" , where , null, null , "id" , null);
				cursor.moveToFirst();
				while(!cursor.isAfterLast()){
					Lista.add(new ElementoComentario(cursor.getString(1),cursor.getString(2)));
					idmax = cursor.getString(0);
					cursor.moveToNext();
				}

				publishProgress(null);
				
				URL url1 = new URL("http://cristianosuniversitarios.org/" +
						"?wpapi=get_posts&dev=1&id="+id);
				InputStream is1 = url1.openStream();
				String result1;
				BufferedReader reader1 = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"),8);
				StringBuilder sb1 = new StringBuilder();
				String line1 = null;
				while ((line1 = reader1.readLine()) != null) {
					sb1.append(line1);
				}
				is1.close();
				result1=sb1.toString();
				JSONObject recep = new JSONObject(result1);

				if(Integer.parseInt((String) recep.getJSONArray("posts").getJSONObject(0).get("comment_count"))==Lista.size())
					return "OK";

				URL url = new URL("http://cristianosuniversitarios.org/" +
						"?wpapi=get_posts&dev=1&id="+id+"&comment=1");
				InputStream is = url.openStream();
				String result;
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				is.close();
				result=sb.toString();

				recep = new JSONObject(result);

				for(int i = 0; i < Integer.parseInt((String) recep.getJSONArray("posts").getJSONObject(0).get("comment_count")); i ++){
					if(Integer.parseInt(idmax)>=Integer.parseInt((String) recep.getJSONArray("posts").getJSONObject(0).get("comment_count")))
						return "OK";
					Lista.add(new ElementoComentario(
							recep.getJSONArray("posts").getJSONObject(0).getJSONArray("comments").getJSONObject(i).getString("author"),
							recep.getJSONArray("posts").getJSONObject(0).getJSONArray("comments").getJSONObject(i).getString("content")
							));
				}


			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

	}

}
